import json

from flask import current_app, jsonify

from . import web
from flask_login import login_required, current_user

from ..models.base import db
from ..models.gift import Gift
from ..view_models.trade import MyTrades


@web.route('/my/gifts')
@login_required
def my_gift():
    uid = current_user.id
    gifts_of_mine = Gift.get_user_gifts(uid)
    isbn_list = [gift.isbn for gift in  gifts_of_mine]
    wish_count_list = Gift.get_wish_counts(isbn_list)
    my_gifts = MyTrades(gifts_of_mine, wish_count_list)
    return json.dumps(my_gifts.gifts, default=lambda o: o.__dict__)

@web.route('/gifts/book/<isbn>')
@login_required
def save_to_gifts(isbn):
    if current_user.can_save_to_list(isbn):
        with db.auto_commit():
            gift = Gift()
            gift.isbn = isbn
            gift.uid = current_user.id
            current_user.beans += current_app.config['BEANS_UPLOAD_ONE_BOOK']
            db.session.add(gift)
            # db.session.commit()
        return jsonify({'meg': '赠送成功！'})
    else:
        return jsonify({'meg': '这本书已经加入你的赠送清单或已存在于你的心愿清单'})

